﻿using JWT;
using JWT.Serializers;
using Pay.Core;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;

namespace Pay.Token {
    public class FormsCookie {
        private string token_key = ConfigurationManager.AppSettings["token_key"];

        public string ValidateToken(string token) {
            try {
                IJsonSerializer serializer = new JsonNetSerializer();
                IDateTimeProvider provider = new UtcDateTimeProvider();
                IJwtValidator validator = new JwtValidator(serializer, provider);
                IBase64UrlEncoder urlEncoder = new JwtBase64UrlEncoder();
                IJwtDecoder decoder = new JwtDecoder(serializer, validator, urlEncoder);
                string decodedJwt = decoder.Decode(token, token_key, true);
                return decodedJwt;
            } catch {
                return "";
            }
        }
        /// <summary>
        /// 创建用户Cookie
        /// </summary>
        /// <param name="name"></param>
        /// <param name="userData"></param>
        /// <param name="remember"></param>
        public void FormsCookieSave(string name, userCookie userData, bool remember) {
            DateTime issueDate = DateTime.Now;
            DateTime expiration = issueDate.Add(FormsAuthentication.Timeout);
            if (remember)
                expiration = DateTime.MaxValue;
            FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, name, issueDate, expiration, false, userData.ToJson());
            string hashTicket = FormsAuthentication.Encrypt(ticket);
            HttpCookie userCookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashTicket);
            if (remember)
                userCookie.Expires = expiration;
            HttpContext.Current.Response.Cookies.Add(userCookie);
        }
    }

    public class userCookie {
        public userCookie() { roles = new List<string>(); }
        public long user_id { get; set; }
        public List<string> roles { get; set; }
    }
}